package codec

import (
	"fmt"
	"gitee.com/visons/gopkg/net/ws"
	"github.com/gorilla/websocket"
)

type textCodec struct {
	conn *websocket.Conn
}

func (self *textCodec) Send(msg interface{}) error {
	return self.conn.WriteMessage(websocket.TextMessage, []byte(msg.(string)))
}

func (self *textCodec) Receive() (interface{}, error) {
	t, msg, err := self.conn.ReadMessage()
	if t != websocket.TextMessage {
		return nil, fmt.Errorf("websocket message is type %d must text", t)
	}
	return string(msg), err
}

func (self *textCodec) Close() error {
	return self.conn.Close()
}

func Text() ws.Protocol {
	return ws.ProtocolFunc(func(conn *websocket.Conn) (ws.Codec, error) {
		return &textCodec{conn}, nil
	})
}
